<?php
namespace Home\Controller;
use Common\Controller\CommonController;
use Home\Controller\SourceController;
class SaleController extends CommonController {
	public function _initialize(){

		parent::_initialize();
	}
	/**
	 * 订售首页
	 */
	public function index(){
		$currency_id=I('currency_id');
		$openid=I('openid');
		$member=$this->getmember($openid);	
		$user=$this->getuser($openid);
		$data['rmb']=$user['money_shangcheng'];
		$sale_money=M('Sale_orders')->where('status = 0 and member_id ='.$member['member_id'])->sum('money');
		$follow_money=M('Sale_orders_follow')->where('status = 0 and member_id ='.$member['member_id'])->sum('money');
		$data['hold_money']=$sale_money+$follow_money;
		$list=M('Sale_config')->where('currency_id ='.$currency_id)->select();
		foreach ($list as $k=>$v){
			$list[$k]['money']=floatval($v['money']);
			$list[$k]['rate']=floatval($v['rate']);
		}
		$data['point_config']=$list;
		$this->ajaxReturn($data,'JSONP');
	
	}
	/**
	 * 获取当前价格
	 */
	public function getPrice(){
		$currency_id=I('currency_id');
		$currency_one=M('Currency')->where('currency_id ='.$currency_id)->find();
		$SOURCE=new SourceController();
		$currency_list=M('Currency')->field('currency_id,currency_name,lever')->where('is_line = 1')->select(); 
		foreach ($currency_list as $k=>$v){
			if(time()%3==0){
				$new_price=round($SOURCE->result($v['currency_id'])->Price*$v['lever'],2);
				$currency_list[$k]['price']=$new_price;
				if(S("huancunsuo")==null){
					S('huancunsuo',"1",100);
					M('Currency_price')->where('currency_id ='.$v['currency_id'])->setField('price',$new_price);
					S('huancunsuo',null);
				}
			}else{
				$currency_list[$k]['price']=M('Currency_price')->where('currency_id ='.$v['currency_id'])->find()['price'];
			}
		}
		$data['currency_list']=$currency_list;
		$result2=$SOURCE->result($currency_id);
		$data['High']=round($result2->High*$currency_one['lever'],2);
		$data['Low']=round($result2->Low*$currency_one['lever'],2);
		$data['price']=round($result->Price*$currency_one['lever'],2);
		$data['time']=time();
		$this->ajaxReturn($data,'JSONP');
	}
	
	/**
	 * 添加订售订单
	 */
	public function add(){
		$arr['status']=0;
		$arr['info']='系统升级中，暂时停止下单';
		$this->ajaxReturn($arr,'JSONP');
		$SOURCE=new SourceController();
		$openid=I('openid');
		$member=$this->getmember($openid);
// 		if($member['member_id']==133||$member['member_id']==723){
// 			$arr['status']=0;
// 			$arr['info']='禁止交易';
// 			$this->ajaxReturn($arr,'JSONP');
// 		}
		$user=$this->getuser($openid);
		//dump($user);die;	
		if(I('money')<0){
			$arr['status']=0;
			$arr['info']='参数错误';
			$this->ajaxReturn($arr,'JSONP');
		}	
		if(I('currency_id')!=28){
		$a=$this->checkTime(I('currency_id'));
			if(!$a){
				$arr['status']=0;
				$arr['info']='交易未开启，请在交易时间内进行交易';
				$this->ajaxReturn($arr,'JSONP');
			}
		}else{
		$b=$this->checkTime2();	
			if(!$b){
				$arr['status']=0;
				$arr['info']='交易未开启，请在交易时间内进行交易';
				$this->ajaxReturn($arr,'JSONP');
			}
		}
		$lastorder=M('Sale_orders')->where('member_id ='.$member['member_id'])->order('add_time desc')->find();
		if(time()-$lastorder['add_time']<10){
			$arr['status']=0;
			$arr['info']='操作频繁，请稍后再试';
			$this->ajaxReturn($arr,'JSONP');
		}
		$checkConfig=M('Sale_config')->where('currency_id ='.I('currency_id').' and id = '.I('sale_type'))->find();
		if(!$checkConfig){
			$arr['status']=0;
			$arr['info']='参数错误';
			$this->ajaxReturn($arr,'JSONP');
		}
		if(I('money_type')==1&&$user['money_shangcheng']<I('money')){
			$arr['status']=0;
			$arr['info']='账户余额不足';
			$this->ajaxReturn($arr,'JSONP');
		}
		if(I('money_type')==2&&$member['ticket']<I('money')){
			$arr['status']=0;
			$arr['info']='体验券不足';
			$this->ajaxReturn($arr,'JSONP');
		}
		$check=$this->checkMoney($user['userid'], $member['member_id']);
		//dump($check);
		if(!$check&&I('money_type')==1){
			$arr1['member_id']=$member['member_id'];
			$arr1['time']=time();
			M('Error_log')->save($arr1);
			$arr['status']=0;
			$arr['info']='账号状态异常';
			$this->ajaxReturn($arr,'JSONP');
		}
		if(I('num')>10){
			$arr['status']=0;
			$arr['info']='单笔最大下单10手';
			$this->ajaxReturn($arr,'JSONP');
		}
		$where['status']=0;
		$where['member_id']=$member['member_id'];
		$where['currency_id']=I('currency_id');
		$sale_count=M('Sale_orders')->where($where)->count();
		$follow_count=M('Sale_orders_follow')->where($where)->count();
		if($sale_count+$follow_count>=30){
			$arr['status']=0;
			$arr['info']='单个合约最大持仓30手';
			$this->ajaxReturn($arr,'JSONP');
		}
		$where_day['member_id']=$member['member_id'];
		$where_day['add_time']=['BETWEEN',[strtotime(date( "Y-m-d", time())),time()]];
		$sale_count2=M('Sale_orders')->where($where_day)->count();
		$follow_count2=M('Sale_orders_follow')->where($where_day)->count();
		if($sale_count2+$follow_count2>=50){
			$arr['status']=0;
			$arr['info']='单个账户每天最大操作50次';
			$this->ajaxReturn($arr,'JSONP');
		}
		$currency=M('Currency')->where('currency_id ='.I('currency_id'))->find();
		$data['order_num']=$member['member_id'].time();
		$data['currency_id']=I('currency_id');
		$data['buy_point']=round($SOURCE->result($currency['currency_id'])->Price*$currency['lever'],2);
		$data['money']=I('money');
		$data['num']=I('num');
		$data['sale_type']=I('sale_type');
		$data['type']=I('type');
		$data['rise_percent']=I('rise_percent');
		$data['fall_percent']=I('fall_percent');  
		$data['add_time']=time();
		$data['status']=0;
		$data['money_type']=I('money_type');
		if(I('rise_percent')!=0){
			$data['rise_money']=I('money')*(1+I('rise_percent')/100);
		}else{
			$data['rise_money']=0;
		}
		if(I('fall_percent')!=0){
			$data['fall_money']=I('money')*(1-I('fall_percent')/100);
		}else{
			$data['fall_money']=I('money')*0.3;
		}
		if(I('money_type')==1){
			$r=$this->addsale($member['member_id'],$data,$openid);
		}
		if(I('money_type')==2){
			$r=$this->addTicketOrder($member['member_id'],$data,$openid);
		}		
		if($r){
			$arr['status']=1;
			$arr['info']='操作成功';
			$this->ajaxReturn($arr,'JSONP');
		}else{
			$arr['status']=0;
			$arr['info']='操作失败';
			$this->ajaxReturn($arr,'JSONP');
		}
	}
	/*
	 * 执行订售操作
	 */
	private function addsale($member_id,$data,$openid){
			//$fee=M('Config')->where(['key' => 'sale_start_fee'])->find()['value'];
			//dump($data);
			$tuijian_bili=$this->config['tuijian_bili'];
			$tuijian_bili2=$this->config['tuijian_bili2'];
			$data['member_id']=$member_id;
			M()->startTrans();
			//添加订单
			$r[]=M('Sale_orders')->add($data);
			//修改金钱
			$where['openId']=$openid;
			$r[]=M('users','wst_')->where($where)->setDec('money_shangcheng',$data['money']);
			$r[]=$this->addFinance($member_id, 1, '添加订单扣除保证金', $data['money'], 2);	
			//添加佣金
			$member=M('Member')->where('member_id ='.$member_id)->find();
			//dump($member);
			if($member['pmember']){
				$pmember=M('Member')->where('member_id ='.$member['pmember'])->find();
				//dump($pmember);
				$r[]=M('Member_money')->where('member_id ='.$pmember['member_id'])->setInc('money2',$tuijian_bili*$data['money']*0.16);
				$arrmoney['member_id']=$member['pmember'];
				$arrmoney['from_id']=$member_id;
				$arrmoney['num']=$tuijian_bili*$data['money'];
				$arrmoney['add_time']=time();
				$arrmoney['type']=2;
				$arrmoney['money_type']=1;
				$r[]=M('Member_money_detail')->add($arrmoney);
				if($pmember['pmember']){
					$ppmember=M('Member')->where('member_id ='.$pmember['pmember'])->find();
					if($ppmember){
						$r[]=M('Member_money')->where('member_id ='.$pmember['pmember'])->setInc('money2',$tuijian_bili2*$data['money']*0.16);
						$arrmoney['member_id']=$ppmember['member_id'];
						$arrmoney['from_id']=$pmember['member_id'];
						$arrmoney['num']=$tuijian_bili2*$data['money'];
						$arrmoney['add_time']=time();
						$arrmoney['type']=2;
						$arrmoney['money_type']=1;
						$r[]=M('Member_money_detail')->add($arrmoney);
					}
				}
			}
			$follow_list=M('Member_follow')->where('status =1 and follow_id ='.$member_id)->select();
			if(!$follow_list){
				M()->commit();
				return true;
			}else{
				foreach ($follow_list as $k =>$v){
// 				if($v['member_id']==133||$v['member_id']==723){
// 						continue;
// 					}
					$openid2=M('Member')->where('member_id ='.$v['member_id'])->find()['openid'];
					$r[]=$this->addFollow($v['member_id'],$member_id,$data,$v['follow_id'],$v['type'],$v['num'],$openid2);
				}
			}
			if(in_array(false, $r)){			
				M()->rollback();
				return false;
			}else{
				M()->commit();
				return true;
			}
	}
	/**
	 * 执行体验券下单操作
	 */
	public function addTicketOrder($member_id,$data,$openid){
		$data['member_id']=$member_id;
		M()->startTrans();
		//添加订单
		$r[]=M('Sale_orders')->add($data);
		//修改体验券余额
		$where['openid']=$openid;	
		$r[]=M('Member')->where($where)->setDec('ticket',$data['money']);
		if(in_array(false, $r)){
			M()->rollback();
			return false;
		}else{
			M()->commit();
			return true;
		}
	}
	/**
	 * 执行跟单操作
	 */
	private function addFollow($member_id,$follow_id,$data,$follow_id,$type,$num,$openid){
		//dump($type);dump($data);die;
		if($num!=0){
			$money=M('Sale_config')->where('id ='.$data['sale_type'])->find()['money']*$num;
			$data['money']=$money;
			if($data['rise_percent']!=0){
				$data['rise_money']=$money*(1+$data['rise_percent']/100);
			}else{
				$data['rise_money']=$money*2;
			}
			if($data['fall_percent']!=0){
				$data['fall_money']=$money*(1+$data['fall_percent']/100);
			}else{
				$data['fall_money']=$money*0.3;
			}
			$data['num']=$num;
		}else{
			$money=$data['money'];
		}
		$tuijian_bili=$this->config['tuijian_bili'];
		$tuijian_bili2=$this->config['tuijian_bili2'];
		$data['follow_id']=$follow_id;
		//$fee=M('Config')->where(['key' => 'sale_start_fee'])->find()['value'];
		$member=M('Member')->where('member_id ='.$member_id)->find();
		$user=$this->getuser($openid);
		
		//$follow_member=M('Member')->where('member_id ='.$follow_id)->find();
		M()->startTrans();
		if($user['money_shangcheng']<$money){
			$r[]=M('Member_follow')->where('follow_id ='.$follow_id.' and member_id ='.$member_id)->setField('status',0);
			return true;
		}
		$data['member_id']=$member_id;
		//反跟单
		if($type==2){
			if($data['type']==1){	
				$data['type']=2;
			}else if($data['type']==2){
				$data['type']=1;
			}
		}
		$r[]=M('Sale_orders_follow')->add($data);
		$where['openId']=$openid;
		$r[]=M('users','wst_')->where($where)->setDec('money_shangcheng',$data['money']);
		$r[]=$this->addFinance($member_id, 2, '添加跟单扣除保证金', $money, 2);
		//添加佣金
		if($member['pmember']){
			$pmember=M('Member')->where('member_id ='.$member['pmember'])->find();
			$r[]=M('Member_money')->where('member_id ='.$member['pmember'])->setInc('money2',$tuijian_bili*$data['money']*0.16);
			$arrmoney['member_id']=$member['pmember'];
			$arrmoney['from_id']=$member_id;
			$arrmoney['num']=$tuijian_bili*$data['money'];
			$arrmoney['add_time']=time();
			$arrmoney['type']=2;
			$arrmoney['money_type']=1;
			$r[]=M('Member_money_detail')->add($arrmoney);
			if($pmember['pmember']){
			$ppmember=M('Member')->where('member_id ='.$pmember['pmember'])->find();
				if($ppmember){
					$r[]=M('Member_money')->where('member_id ='.$pmember['pmember'])->setInc('money2',$tuijian_bili2*$data['money']*0.16);
					$arrmoney['member_id']=$ppmember['member_id'];
					$arrmoney['from_id']=$pmember['member_id'];
					$arrmoney['num']=$tuijian_bili2*$data['money'];
					$arrmoney['add_time']=time();
					$arrmoney['type']=2;
					$arrmoney['money_type']=1;
					$r[]=M('Member_money_detail')->add($arrmoney);
				}
			}
			
		}
		//$follow_list=M('Member_follow')->where('status =1 and follow_id ='.$member_id)->select();
		if(in_array(false, $r)){
			M()->rollback();
			return false;
		}else{
			M()->commit();
			return true;
		}
	}
	/**
	 * 手动平仓订售订单
	 */
	public function balance_one(){
		$sale_id=I('id');
		$sale_order=M('Sale_orders')->where('id ='.$sale_id)->find();
		if($sale_order['currency_id']!=28){
			$a=$this->checkTime($sale_order['currency_id']);
				if(!$a){
					$arr['status']=0;
					$arr['info']='交易未开启，请在交易时间内进行交易';
					$this->ajaxReturn($arr,'JSONP');
					}
			}else{
				$b=$this->checkTime2();
				if(!$b){
					$arr['status']=0;
					$arr['info']='交易未开启，请在交易时间内进行交易';
					$this->ajaxReturn($arr,'JSONP');
				}
		}
		//echo 1;die;
		//获取最新价格
		$SOURCE=new SourceController();
		$lever=M('Currency')->where('currency_id ='.$sale_order['currency_id'])->find()['lever'];
		$result=$SOURCE->result($sale_order['currency_id']);
		$new_price=round($result->Price*$lever,2);
		$r[]=$this->balance($sale_id,$new_price);
		$follow_order=M('Sale_orders_follow')->where('order_num ='.$sale_order['order_num'])->select();
		//dump($follow_order);die;
		if(!empty($follow_order)){
			foreach ($follow_order as $k =>$v){
				$r[]=$this->balanceFollow($v['id'],$new_price);
			}
		}
		//dump($r);		
		if(in_array(false, $r)){
			$arr['status']=0;
			$arr['info']='操作频繁';
			$this->ajaxReturn($arr,'JSONP');
		}else{
			$arr['status']=1;
			$arr['info']='操作成功';
			$this->ajaxReturn($arr,'JSONP');
		}
		
	}
	
	/**
	 * 一键平仓
	 */
	public function balance_all(){
		$openid=I('openid');
		$member=$this->getmember($openid);
		$user=$this->getuser($openid);
		$sale_list=M('Sale_orders')->where('status = 0 and member_id ='.$member['member_id'])->select();
		if(!$sale_list){
			$arr['status']=0;
			$arr['info']='没有订单，操作失败';
			$this->ajaxReturn($arr,'JSONP');
		}
		foreach ($sale_list as $k=>$v){
			if($v['currency_id']!=28){
				$a=$this->checkTime($v['currency_id']);
				if(!$a){
					$arr['status']=0;
					$arr['info']='交易未开启，请在交易时间内进行交易';
					$this->ajaxReturn($arr,'JSONP');
				}
			}else{
				$b=$this->checkTime2();
				if(!$b){
					$arr['status']=0;
					$arr['info']='交易未开启，请在交易时间内进行交易';
					$this->ajaxReturn($arr,'JSONP');
				}
			}
			//获取最新价格
			$SOURCE=new SourceController();
			$lever=M('Currency')->where('currency_id ='.$v['currency_id'])->find()['lever'];
			$result=$SOURCE->result($v['currency_id']);
			$new_price=round($result->Price*$lever,2);
			$r[]=$this->balance($v['id'],$new_price);
			$sale_list_follow=M('Sale_orders_follow')->where('order_num ='.$v['order_num'])->select();
			if($sale_list_follow){
				foreach ($sale_list_follow as $k2=>$v2){
					$r[]=$this->balanceFollow($v2['id'],$new_price);
				}
			}
		}
		//dump($r);
		if(in_array(false, $r)){
			$arr['status']=0;
			$arr['info']='操作失败';
			$this->ajaxReturn($arr,'JSONP');
		}else{
			$arr['status']=1;
			$arr['info']='操作成功';
			$this->ajaxReturn($arr,'JSONP');
		}
	}
	
	/**
	 * 结算订售单
	 */
	
	private function balance($sale_id,$new_price){
		$fee=M('Config')->where(['key' => 'day_fee'])->find()['value'];
		$score=M('Config')->where(['key' => 'score_percent'])->find()['value'];
		$sale=M('Sale_orders')->where('id ='.$sale_id)->find();
		if($sale['status']==1){
			return false;
		}
		$openid=M('Member')->where('member_id ='.$sale['member_id'])->find()['openid'];
		$a=$this->checkTime($sale['currency_id']);
		if(!$a){
			return false;
		}
		$sale_config=M('Sale_config')->where('id ='.$sale['sale_type'])->find();
		$rate=$sale_config['rate'];
		$fee_end=$sale_config['fee']*$sale['money'];
		//体验券下单结算
		if($sale['money_type']==2){
			if($sale['type']==1){
				//计算隔夜费
				$sale_orders=M('Sale_orders')->where('id ='.$sale_id)->find();
				$daynum=$this->checkDay($sale_orders['add_time'], time());
				$fee_all=$sale['money']*$daynum*$fee;
				//修改订单状态
				$profit=($new_price-$sale['buy_point'])*$rate;
				$arr['trade_time']=time();
				$arr['status']=1;
				$arr['profit']=$profit;
				$arr['pc_price']=$new_price;
				$arr['day_fee']=$fee_all;
				$arr['fee']=$fee_end;
				//修改订单状态
				$r[]=M('Sale_orders')->where('id ='.$sale_id)->save($arr);
				if($profit>($fee_end+$fee_all)){
					//添加平仓金钱
					$where['openId']=$openid;
					$r[]=M('users','wst_')->where($where)->setInc('money_shangcheng',$profit-$fee_end-$fee_all);
				}
				if(in_array(false, $r)){
					return false;
				}else{
					return true;
				}
			}
			if($sale['type']==2){
				//计算隔夜费
				$sale_orders=M('Sale_orders')->where('id ='.$sale_id)->find();
				$daynum=$this->checkDay($sale_orders['add_time'], time());
				$fee_all=$sale['money']*$daynum*$fee;
				//修改订单状态
				$profit=($sale['buy_point']-$new_price)*$rate;
				$arr['trade_time']=time();
				$arr['status']=1;
				$arr['profit']=$profit;
				$arr['pc_price']=$new_price;
				$arr['day_fee']=$fee_all;
				$arr['fee']=$fee_end;
				$r[]=M('Sale_orders')->where('id ='.$sale_id)->save($arr);
				if($profit>($fee_end+$fee_all)){
					//添加平仓金钱
					$where['openId']=$openid;
					$r[]=M('users','wst_')->where($where)->setInc('money_shangcheng',$profit-$fee_end-$fee_all);
				}
				//$r[]=M('Sale_orders')->where('id ='.$sale_id)->save($arr);
				//修改订单状态
				if(in_array(false, $r)){
					return false;
				}else{
					return true;
				}
			}	
		}
		if($sale['type']==1){
			//修改订单状态
			$profit=($new_price-$sale['buy_point'])*$rate*$sale['num'];
			$arr['trade_time']=time();
			$arr['status']=1;
			$arr['profit']=$profit;
			$arr['pc_price']=$new_price;
			//添加平仓金钱
			$where['openId']=$openid;
			$r[]=M('users','wst_')->where($where)->setInc('money_shangcheng',$sale['money']+$profit);
			$r[]=$this->addFinance($sale['member_id'], 3, '订单结算返还金额', $sale['money']+$profit, 1);
			//加积分
			$r[]=M('users','wst_')->where($where)->setInc('score',$sale['money']*$score);
			//扣除手续费
			$r[]=M('users','wst_')->where($where)->setDec('money_shangcheng',$fee_end);
			$r[]=$this->addFinance($sale['member_id'], 4, '订单结算扣除手续费', $fee_end, 2);
			//计算隔夜费
			$sale_orders=M('Sale_orders')->where('id ='.$sale_id)->find();
			$daynum=$this->checkDay($sale_orders['add_time'], time());
			//dump($daynum);
			$fee_all=$sale['money']*$daynum*$fee;
			if($fee_all!=0){
			$r[]=M('users','wst_')->where($where)->setDec('money_shangcheng',$fee_all);
			$r[]=$this->addFinance($sale['member_id'], 5, '订单结算扣除仓储管理费', $fee_all, 2);
			}
			$arr['day_fee']=$fee_all;
			$arr['fee']=$fee_end;
			//修改订单状态
			$r[]=M('Sale_orders')->where('id ='.$sale_id)->save($arr);
			//添加日志
			$day=date('d',time());
			$month=date('m',time());
			$year=date('Y',time());
			$a=M('Profit_log')->where('year ='.$year.' and month ='.$month.' and day ='.$day.' and member_id ='.$sale['member_id'])->find();
			if($a){
				$r[]=M('Profit_log')->where('year ='.$year.' and month ='.$month.' and day ='.$day.' and member_id ='.$sale['member_id'])->setInc('money',$sale['money']);
				$r[]=M('Profit_log')->where('year ='.$year.' and month ='.$month.' and day ='.$day.' and member_id ='.$sale['member_id'])->setInc('profit',$profit);
			}else{
				$arr2['member_id']=$sale['member_id'];
				$arr2['year']=$year;
				$arr2['month']=$month;
				$arr2['day']=$day;
				$arr2['money']=$sale['money'];
				$arr2['profit']=$profit;
				$r[]=M('Profit_log')->add($arr2);
			}	
			if(in_array(false, $r)){
				return false;
			}else{
				return true;
			}
		}
		if($sale['type']==2){
			$profit=($sale['buy_point']-$new_price)*$rate*$sale['num'];
			$arr['trade_time']=time();
			$arr['status']=1;
			$arr['profit']=$profit;
			$arr['pc_price']=$new_price;
			//添加平仓金钱
			$where['openId']=$openid;
			$r[]=M('users','wst_')->where($where)->setInc('money_shangcheng',$sale['money']+$profit);
			$r[]=$this->addFinance($sale['member_id'], 3, '订单结算返还金额', $sale['money']+$profit, 1);
			//加积分
			$r[]=M('users','wst_')->where($where)->setInc('score',$sale['money']*$score);
			//扣除手续费
			$r[]=M('users','wst_')->where($where)->setDec('money_shangcheng',$fee_end);
			$r[]=$this->addFinance($sale['member_id'], 4, '订单结算扣除手续费', $fee_end, 2);
			//计算隔夜费
			$sale_orders=M('Sale_orders')->where('id ='.$sale_id)->find();
			$daynum=$this->checkDay($sale_orders['add_time'], time());
			$fee_all=$sale['money']*$daynum*$fee;
			if($fee_all!=0){
			$r[]=M('users','wst_')->where($where)->setDec('money_shangcheng',$fee_all);
			$r[]=$this->addFinance($sale['member_id'], 5, '订单结算扣除仓储管理费', $fee_all, 2);
			}
			$arr['day_fee']=$fee_all;
			$arr['fee']=$fee_end;
			//修改订单状态
			$r[]=M('Sale_orders')->where('id ='.$sale_id)->save($arr);
			//添加日志
			$day=date('d',time());
			$month=date('m',time());
			$year=date('Y',time());
			$a=M('Profit_log')->where('year ='.$year.' and month ='.$month.' and day ='.$day.' and member_id ='.$sale['member_id'])->find();
			if($a){
				$r[]=M('Profit_log')->where('year ='.$year.' and month ='.$month.' and day ='.$day.' and member_id ='.$sale['member_id'])->setInc('money',$sale['money']);
				$r[]=M('Profit_log')->where('year ='.$year.' and month ='.$month.' and day ='.$day.' and member_id ='.$sale['member_id'])->setInc('profit',$profit);
			}else{
				$arr2['member_id']=$sale['member_id'];
				$arr2['year']=$year;
				$arr2['month']=$month;
				$arr2['day']=$day;
				$arr2['money']=$sale['money'];
				$arr2['profit']=$profit;
				$r[]=M('Profit_log')->add($arr2);
			}
			if(in_array(false, $r)){
				return false;
			}else{
				return true;
			}
		}
	}
	/**
	 * 结算跟单
	 */
	
	public function balanceFollow($sale_id,$new_price){
		$score=$this->config['score_percent'];
		//$score=M('Config')->where(['key' => 'score_percent'])->find()['value'];
		$fee=$this->config['day_fee'];
		//$fee=M('Config')->where(['key' => 'day_fee'])->find()['value'];
		$follow_percent=$this->config['follow_config'];
		//$follow_percent=M('Config')->where(['key' => 'follow_config'])->find()['value'];
		$sale=M('Sale_orders_follow')->where('id ='.$sale_id)->find();
		if($sale['status']==1){
			return true;
		}
		$openid=M('Member')->where('member_id ='.$sale['member_id'])->find()['openid'];
		$sale_config=M('Sale_config')->where('id ='.$sale['sale_type'])->find();
		$rate=$sale_config['rate'];
		$fee_end=$sale_config['fee']*$sale['money'];
		if($sale['type']==1){
			//修改订单状态
			$profit=($new_price-$sale['buy_point'])*$rate*$sale['num'];
			$arr['trade_time']=time();
			$arr['status']=1;
			$arr['profit']=$profit;
			$arr['pc_price']=$new_price;
			//添加平仓金钱
			$where['openId']=$openid;
			$r[]=M('users','wst_')->where($where)->setInc('money_shangcheng',$sale['money']+$profit);
			$r[]=$this->addFinance($sale['member_id'], 6, '跟单结算返还金额', $sale['money']+$profit, 1);
			//加积分
			$r[]=M('users','wst_')->where($where)->setInc('score',$sale['money']*$score);
			if($sale['follow_status']==1){
				//添加佣金
				$r[]=M('Member_money')->where('member_id ='.$sale['follow_id'])->setInc('money1',$fee_end*$follow_percent);
				$arrmoney['member_id']=$sale['follow_id'];
				$arrmoney['from_id']=$sale['member_id'];
				$arrmoney['num']=$fee_end*$follow_percent;
				$arrmoney['add_time']=time();
				$arrmoney['type']=1;
				$arrmoney['money_type']=1;
				$r[]=M('Member_money_detail')->add($arrmoney);
			}
			//扣除手续费
			$r[]=M('users','wst_')->where($where)->setDec('money_shangcheng',$fee_end);
			$r[]=$this->addFinance($sale['member_id'], 7, '跟单结算扣除手续费', $fee_end, 2);
			//计算隔夜费
			$sale_orders=M('Sale_orders_follow')->where('id ='.$sale_id)->find();
			$daynum=$this->checkDay($sale_orders['add_time'],time());
			$fee_all=$sale['money']*$daynum*$fee;
			if($fee_all!=0){
			$r[]=M('users','wst_')->where($where)->setDec('money_shangcheng',$fee_all);
			$r[]=$this->addFinance($sale['member_id'], 8, '跟单结算扣除仓储管理费', $fee_all, 2);
			}
			$arr['day_fee']=$fee_all;
			$arr['fee']=$fee_end;
			//修改订单状态
			$r[]=M('Sale_orders_follow')->where('id ='.$sale_id)->save($arr);
			//dump($r);
			if(in_array(false, $r)){
				return false;
			}else{
				return true;
			}
		}
		if($sale['type']==2){
			$profit=($sale['buy_point']-$new_price)*$rate*$sale['num'];
			$arr['trade_time']=time();
			$arr['status']=1;
			$arr['profit']=$profit;
			$arr['pc_price']=$new_price;
			//添加平仓金钱
			$where['openId']=$openid;
			$r[]=M('users','wst_')->where($where)->setInc('money_shangcheng',$sale['money']+$profit);
			$r[]=$this->addFinance($sale['member_id'], 6, '跟单结算返还金额', $sale['money']+$profit, 1);
			//加积分
			$r[]=M('users','wst_')->where($where)->setInc('score',$sale['money']*$score);
			//添加佣金
			$r[]=M('Member_money')->where('member_id ='.$sale['follow_id'])->setInc('money1',$fee_end*$follow_percent);
			$arrmoney['member_id']=$sale['follow_id'];
			$arrmoney['from_id']=$sale['member_id'];
			$arrmoney['num']=$fee_end*$follow_percent;
			$arrmoney['add_time']=time();
			$arrmoney['type']=1;
			$arrmoney['money_type']=1;
			$r[]=M('Member_money_detail')->add($arrmoney);
			//扣除手续费
			$r[]=M('users','wst_')->where($where)->setDec('money_shangcheng',$fee_end);
			$r[]=$this->addFinance($sale['member_id'], 7, '跟单结算扣除手续费', $fee_end, 2);
			//计算隔夜费
			$sale_orders=M('Sale_orders_follow')->where('id ='.$sale_id)->find();
			$daynum=$this->checkDay($sale_orders['add_time'], time());
			$fee_all=$sale['money']*$daynum*$fee;
			if($fee_all!=0){
			$r[]=M('users','wst_')->where($where)->setDec('money_shangcheng',$fee_all);
			$r[]=$this->addFinance($sale['member_id'], 8, '跟单结算扣除仓储管理费', $fee_all, 2);
			}
			$arr['day_fee']=$fee_all;
			$arr['fee']=$fee_end;
			//修改订单状态
			$r[]=M('Sale_orders_follow')->where('id ='.$sale_id)->save($arr);
			if(in_array(false, $r)){
				return false;
			}else{
				return true;
			}
		}
	}
	/**
	 * 判断隔夜天数
	 */
	private  function checkDay($startTime,$endTime){
		$times=0;
		$starthour=date('H',$startTime);//8
		$endhour = date('H',$endTime);//10
		if($starthour<4){
			$time=strtotime("today 04:00:00",$startTime);
			for($i=1;$i<10000;$i++){
				if($endTime>$time+($i-1)*3600*24){
							$times=$i;
				}else{
					break;
				}
			}
		}
		else{
			$time=strtotime("+1day 04:00:00",$startTime);
			for($i=1;$i<10000;$i++){
				if($endTime>$time+($i-1)*3600*24){				
						$times=$i;
				}else{
					break;
				}
			}
		}
		return $times;
	}
	
	
	
	/**
	 * 持仓查询
	 */
	public function saleHold(){
		$openid=I('openid');
		$member=$this->getmember($openid);
		$SOURCE=new SourceController();
		//计算当日订售单数
		$where['member_id']=$member['member_id'];
		$where['add_time']=['BETWEEN',[strtotime(date( "Y-m-d", time())),time()]];
		$sale_count=M('Sale_orders')->where($where)->count();
		$data['sale_count']=$sale_count;
		//计算当日订售平仓收益
		$sale_profit=M('Sale_orders')->where($where)->where('status = 1')->sum('profit');
		if(empty($sale_profit)){
			$sale_profit=0;
		}
		$data['sale_profit']=$sale_profit;
		//计算未平仓浮动收益
		$sale_orders=M('Sale_orders')->where('status = 0 and member_id ='.$member['member_id'])->select();
		$profit_all=0;
		$currency_list=M('Currency')->where('is_line = 1')->select();
		foreach ($currency_list as $k=>$v){
			$array[$v['currency_id']]=$SOURCE->result($v['currency_id'])->Price*$v['lever'];
		}
		//dump($array[25]);
		foreach ($sale_orders as $kk =>$vv){
			$currency=M('Currency')->where('currency_id ='.$vv['currency_id'])->find();
			$sale_config=M('Sale_config')->where('id = '.$vv['sale_type'])->find();
			$now_price=$array[$vv['currency_id']];
			$sale_orders[$kk]['now_price']=round($now_price,2);
			$sale_orders[$kk]['currency_name']=$currency['currency_name'];
			if(round($now_price,2)==$vv['buy_point']){
				$sale_orders[$kk]['profit']=0;
			}else{
				if($vv['type']==1){
					$sale_orders[$kk]['profit']=$vv['num']*floatval(round(($now_price-$vv['buy_point'])*$sale_config['rate'],2));
					$profit_all+=$vv['num']*floatval(round(($now_price-$vv['buy_point'])*$sale_config['rate'],2));
				}
				if($vv['type']==2){
					$sale_orders[$kk]['profit']=$vv['num']*floatval(round(($vv['buy_point']-$now_price)*$sale_config['rate'],2));
					$profit_all+=$vv['num']*floatval(round(($vv['buy_point']-$now_price)*$sale_config['rate'],2));
				}
			}
		}
		$data['list']=$sale_orders;
		$data['profit_float']=$profit_all;
		$this->ajaxReturn($data,'JSONP');
	}
	
	/**
	 * 平仓查询
	 */
	public function saleBalance(){
		$openid=I('openid');
		$member=$this->getmember($openid);
		$list=M('Sale_orders')->where('status = 1 and member_id ='.$member['member_id'])->order('trade_time desc')->select();
		foreach ($list as $k =>$v){
			$list[$k]['currency_name']=M('Currency')->where('currency_id ='.$v['currency_id'])->find()['currency_name'];
		}
		$data['list']=$list;
		$this->ajaxReturn($data,'JSONP');
	}
	/**
	 * 跟单记录查询
	 */
	public function followRecord(){
		$rmb=M('Member')->where('member_id ='.$_SESSION['member_id'])->find()['rmb'];
		$data['rmb']=$rmb;
		$where1['member_id']=$_SESSION['member_id'];
		$where1['add_time']=['BETWEEN',[strtotime(date( "Y-m-d", time())),time()]];
		$sale_count_day=M('Sale_orders_follow')->where($where1)->count();
		$sale_count_all=M('Sale_orders_follow')->where('member_id ='.$_SESSION['member_id'])->count();
		$data['sale_count_all']=$sale_count_all;
		$data['sale_count_day']=$sale_count_day;
		if(!empty(I('type'))){
			$where['type']=I('type');
		}
		if(!empty(I('status'))){
			$where['status']=I('status');
		}
		$where['member_id']=$_SESSION['member_id'];
		$list=M('Sale_orders_follow')->where($where)->select();
		if($list){
			$data['list']=$list;
			$data['status']=1;
			$this->ajaxReturn($data,'JSONP');
		}else{
			$data['list']='';
			$data['status']=0;
			$this->ajaxReturn($data,'JSONP');
		}
	}
	/*
	 * 修改止盈止损点数
	 */
	
	public function changePercent(){
		$id=I('id');
		$rise_percent=I('rise_percent');
		$fall_percent=I('fall_percent');
		$orders=M('Sale_orders')->where('id ='.$id)->find();
		$arr['rise_percent']=$rise_percent;
		$arr['fall_percent']=$fall_percent;
		if($rise_percent==$orders['rise_percent']&&$fall_percent==$orders['fall_percent']){
			$data['status']=0;
			$data['info']='请不要重复操作';
			$this->ajaxReturn($data,'JSONP');
		}
		if($rise_percent!=0){
			$arr['rise_money']=(1+$rise_percent/100)*$orders['money'];
		}else{
			$arr['rise_money']=0;
		}
		if($fall_percent!=0){
			$arr['fall_money']=(1-$fall_percent/100)*$orders['money'];
		}else{
			$arr['fall_money']=$orders['money']*0.3;
		}
		$r=M('Sale_orders')->where('id ='.$id)->save($arr);
		if($r){
			$data['status']=1;
			$data['info']='操作成功';
			$this->ajaxReturn($data,'JSONP');
		}else{
			$data['status']=0;
			$data['info']='操作失败';
			$this->ajaxReturn($data,'JSONP');
		}
	}
	/**
	 * 检测交易时间
	 */
	private function checkTime($currency_id){
		$currency=M('Currency')->where('currency_id ='.$currency_id)->find();
		if($currency['is_lock']==1){
			return false;
		}
		$time=strtotime(date('Y-m-d'));
		$start_time=$time+$currency['start_time_h']*3600+$currency['start_time_m']*60;
		$over_time=$time+$currency['end_time_h']*3600+$currency['end_time_m']*60;
		$start_x_time=$time+$currency['start_time_x_h']*3600+$currency['start_time_x_m']*60;
		$over_x_time=$time+$currency['end_time_x_h']*3600+$currency['end_time_x_m']*60;
		if((time()<$start_time||time()>$over_time)  &&  (time()<$start_x_time||time()>$over_x_time)){
			return false;
		}
		$week = date("l"
				,time());  //获取当前日期是周几
		$hour= date("H",time());
		if($week == 'Saturday' && $currency['is_lock_6'] == 1&&$hour>=4){
			return false;
		}
		if($week == 'Sunday' && $currency['is_lock_7'] == 1 ){
			return false;
		}
		return true;
	}
	/**
	 * 恒指检测交易时间
	 */
	private function checkTime2(){
		$currency=M('Currency')->where('currency_id = 28')->find();
		if($currency['is_lock']==1){
			return false;
		}
		$time=time();
		$hour=date("G",time());
		$week = date("l",time());  //获取当前日期是周几
		if($week == 'Saturday'&&$hour>=1){
			return false;
		}
		if($week == 'Sunday'){
			return false;
		}
		$time1=strtotime('09:15:00',$time);
		$time2=strtotime('12:00:00',$time);
		$time3=strtotime('13:00:00',$time);
		$time4=strtotime('16:30:00',$time);
		$time5=strtotime('17:15:00',$time);
		$time6=strtotime('23:59:59',$time);
		$time7=strtotime('00:00:00',$time);
		$time8=strtotime('01:00:00',$time);
		if(($time<$time1||$time>$time2) && ($time<$time3||$time>$time4) && ($time<$time5||$time>$time6)&&($time<$time7||$time>$time8)){
			return false;
		}
		return true;
	}
	public function change(){
		$list=M('Sale_orders')->where('profit = fall_money - money and status = 1 and num != 1 and trade_time < 1516074000')->select();
		foreach ($list as $k=>$v){
			if($v['type']==1){
				$price=($v['buy_point']-$v['pc_price'])/$v['num'];
				$arr['pc_price']=$v['buy_point']-$price;
				M('Sale_orders')->where('id ='.$v['id'])->save($arr);
			}
			if($v['type']==2){
				$price=($v['pc_price']-$v['buy_point'])/$v['num'];
				$arr['pc_price']=$v['buy_point']+$price;
				M('Sale_orders')->where('id ='.$v['id'])->save($arr);
			}
		}
	}
	private function checkMoney($uid,$member_id){
		$recharge=M('Recharge','wst_')->where('uid ='.$uid)->select();
		$pay=M('Pay')->where('member_id ='.$member_id)->select();
		$pmember=M('Member')->where('pmember ='.$member_id)->select();
		$tiyan=M('Sale_orders')->where('money_type = 2 and status = 1')->find();
		if($tiyan['profit']>($tiyan['fee']+$tiyan['day_fee'])){
			$r=true;
		}else{
			$r=false;
		}
		if(!$pay&&!$recharge&&!$pmember&&$r){
			return false;
		}else{
			return true;
		}
	}
}